<template>
  <div class="container mx-auto px-4 py-6">
    <!-- 页面标题 -->
    <div style="display: grid; justify-content: center; align-items: center;">
      <h1 class="text-2xl font-bold text-gray-800 mb-6">奖惩管理</h1>
    </div>


    <!-- 操作区域：新增 -->
    <div class="action-bar bg-white rounded-lg shadow-md p-4 mb-6 flex justify-end">
      <div class="search-container flex-1 flex">
        <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索名称..."
            class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
        >
        <button
            @click="selectData"
            class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-r-md transition-colors"
        >
          <i class="fa fa-search mr-2">搜索</i>
        </button>
      </div>
      <button @click="openAddModal" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md transition-colors flex items-center">
        <i class="fa fa-plus mr-2"></i>新增奖惩
      </button>
    </div>

    <!-- 表格 -->
    <div class="table-container w-full bg-white rounded-lg shadow-md overflow-hidden">
      <table class="reward-table w-full">
        <thead>
        <tr class="bg-gray-50">
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">教师号</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">教师姓名</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">级别</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
        </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
        <tr v-for="(reward,index) in rewards" :key="reward.id" class="hover-row hover:bg-gray-50 transition-colors">
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reward.id }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reward.teacherId }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reward.teacherName }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reward.type === 1 ? '奖励' : '惩罚' }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reward.type === 1 ? rewards_[reward.level-1].name: punishs[reward.level-1].name}}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reward.date }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
            <button
                @click=openEditModal(reward.teacherId)
                class="text-green-500 hover:text-green-700 transition-colors mr-3"
            >
              <i class="fa fa-pencil mr-1"></i>编辑
            </button>
            <button
                @click="deleteReward(reward.id,index)"
                class="text-red-500 hover:text-red-700 transition-colors mr-3"
            >
              <i class="fa fa-trash mr-1"></i>删除
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 空状态提示 -->
    <div v-if="rewards.length === 0" class="empty-state w-full bg-white rounded-lg shadow-md p-8 text-center">
      <div class="empty-icon text-6xl text-gray-400 mb-4">
        <i class="fa fa-folder-open-o"></i>
      </div>
      <p class="text-gray-600 mb-4">暂无奖惩数据</p>
      <button @click="openAddModal" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors">
        <i class="fa fa-plus mr-2"></i>添加奖惩
      </button>
    </div>

    <!-- 查看、新增、编辑教师模态框 -->
    <div v-if="showViewModal || showAddModal || showEditModal" class="modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="modal-content bg-white rounded-lg shadow-xl w-full max-w-4xl transform transition-all">
        <div class="modal-header flex justify-between items-center p-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">
            {{ showViewModal ? '查看奖惩' : (showEditModal ? '编辑奖惩' : '新增奖惩') }}
          </h3>
          <button @click="closeModal" class="text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <div class="modal-body p-4">
          <div>
            <div class="flex justify-between items-center mb-4">
              <h4 class="text-base font-medium text-gray-900 flex items-center">
                <span class="inline-block w-2 h-2 bg-orange-500 rounded-full mr-2"></span>
                奖惩记录
              </h4>
              <button
                  v-if="!showViewModal"
                  @click="openRewardModal"
                  class="text-sm text-orange-600 hover:text-orange-700 flex items-center"
              >
                <i class="fa fa-plus-circle mr-1"></i>添加记录
              </button>
            </div>
            <div class="modal-body p-4">

              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">教师号</label>
                <div
                    v-if="showEditModal"
                    class="form-control w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-100"
                >
                  {{ editingReward.teacherId }}
                </div>
                <select
                    v-if="!showEditModal"
                    v-model="editingReward.teacherId"
                    class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    required
                >
                  <option value="">请输入教师号...</option>
                  <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">{{teacher.id}} - {{ teacher.name }}</option>
                  <p v-if="rewardErrors.teacherId" class="mt-1 text-red-500 text-sm">{{ rewardErrors.teacherId }}</p>
                </select>
              </div>

              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">教师名称</label>
                <div
                    v-if="showEditModal"
                    class="form-control w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-100"
                >
                  {{ editingReward.teacherName }}
                </div>
                <select
                    v-if="!showEditModal"
                    v-model="editingReward.teacherName"
                    class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    required
                >
                  <option value="">请输入教师名...</option>
                  <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.name">{{teacher.id}} - {{ teacher.name }}</option>
                  <p v-if="rewardErrors.teacherId" class="mt-1 text-red-500 text-sm">{{ rewardErrors.teacherId }}</p>
                </select>

              </div>

              <div class="form-group">
                <div class="flex space-x-4">
                  <label class="block text-sm font-medium text-gray-700 mb-1">类型</label>
                  <label class="inline-flex items-center">
                    <input type="radio" v-model.number="editingReward.type" value="1" class="form-radio h-4 w-4 text-green-500">
                    <span class="ml-2 text-sm text-gray-700">奖励</span>
                  </label>
                  <label class="inline-flex items-center">
                    <input type="radio" v-model.number="editingReward.type" value="2" class="form-radio h-4 w-4 text-red-500">
                    <span class="ml-2 text-sm text-gray-700">惩罚</span>
                  </label>
                </div>
                <p v-if="rewardErrors.type" class="mt-1 text-red-500 text-sm">{{ rewardErrors.type }}</p>
              </div>

              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">级别</label>
                <select
                    v-model="editingReward.level"
                    class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    required
                >
                  <option value="">请输入奖惩级别...</option>
                  <option  v-if="editingReward.type ==1" v-for="reward in rewards_" :key="reward.id" :value="reward.type">{{reward.type}} - {{ reward.name }}</option>
                  <option  v-if="editingReward.type ==2" v-for="punish in punishs" :key="punish.id" :value="punish.type">{{punish.type}} - {{ punish.name }}</option>
                  <p v-if="rewardErrors.teacherId" class="mt-1 text-red-500 text-sm">{{ rewardErrors.teacherId }}</p>
                </select>
                <p v-if="rewardErrors.level" class="mt-1 text-red-500 text-sm">{{ rewardErrors.level }}</p>
              </div>

              <div class="form-group">
                <label class="block text-sm font-medium text-gray-700 mb-1">日期</label>
                <input
                    type="date"
                    v-model="editingReward.date"
                    class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                <p v-if="rewardErrors.date" class="mt-1 text-red-500 text-sm">{{ rewardErrors.date }}</p>
              </div>
            </div>

            <div class="modal-footer flex justify-end p-4 border-t border-gray-200">
              <button @click="closeRewardModal" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors">
                取消
              </button>
              <button @click="saveReward" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors">
                确认
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>




    </div>

</template>


<script setup>
import { ref, onMounted, watch } from 'vue'

// 状态管理
const rewards = ref([])
const punishs = ref([
  {
    name:"较轻",
    type:"1"
  },
  {
    name:"严重",
    type:"2"
  },
  {
    name:"极其严重",
    type:"3"
  }
])

const rewards_ = ref([
  {
    name:"较好",
    type:"1"
  },
  { name:"很好",
    type:"2"
  },
  {
    name:"优秀",
    type:"3"
  }
])

const searchQuery = ref("")

const selectData = async () => {
  if (searchQuery.value.toString().trim() === "") return
  const famRes = await fetch(`/api/reward-punishment/${searchQuery.value}`)
  const famData = await famRes.json()
  rewards.value = famData.data || []
}

const showViewModal = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const errors = ref({})
const teachers = ref([])
// 奖惩相关状态
const showRewardModal = ref(false)
const editingReward = ref({
  id: null,
  teacherId: null,
  teacherName: null,
  type: null,
  level: '',
  date: new Date().toISOString().split('T')[0]
})
const rewardErrors = ref({})

// 生命周期钩子：页面加载时获取初始数据
onMounted(() => {
  fetchInitialData()
})

// 获取初始数据（部门、职务、职称、教师列表）
const fetchInitialData = async () => {

  try {
    const redRes = await fetch('/api/reward-punishment')
    const redData = await redRes.json()
    if (redRes.ok && redData.code === 200) {
      rewards.value = redData.data || []
    }
    const teacherRes = await fetch('/api/teacher')
    const teacherData = await teacherRes.json()
    if (teacherRes.ok && teacherData.code === 200) {
      teachers.value = teacherData.data || []
    }
  } catch (error) {
    alert(`获取初始化数据失败：${error.message}`)
    console.error('获取初始化数据失败:', error)
  }
}


// 打开新增模态框
const openAddModal = () => {
  // 重置表单数据和错误
  editingReward.value = {
    id: null,
    teacherId: null,
    teacherName: null,
    type: null,
    level: '',
    date: new Date().toISOString().split('T')[0]
  }
  errors.value = {}
  showAddModal.value = true
  showViewModal.value = false
  showEditModal.value = false
}

// 打开编辑模态框
const openEditModal = (id) => {
  fetch(`/api/reward-punishment/${id}`,{method:'Get'})
      .then(response => response.json())
      .then(data => {
        if (data.code === 200) {
          editingReward.value = data.data[0] || []
          console.log(editingReward.value)
        } else {
          throw new Error(data.msg || '获取教师信息失败')
        }
      })
      .catch(error => {
        alert(`获取奖惩信息失败：${error.message}`)
        console.error('获取奖惩信息失败:', error)
      })
  showEditModal.value = true
  showAddModal.value = false
  showViewModal.value = false
}

// 关闭模态框
const closeModal = () => {
  showViewModal.value = false
  showAddModal.value = false
  showEditModal.value = false
  errors.value = {}
}

// 打开奖惩模态框
const openRewardModal = () => {
  if(showEditModal.value) {
    return
  }
  editingReward.value = {
    id: null,
    teacherId: null,
    teacherName: null,
    type: null, // 默认奖励
    level: '',
    date: new Date().toISOString().split('T')[0]
  }
  rewardErrors.value = {}
  showRewardModal.value = true
}

// 关闭奖惩模态框
const closeRewardModal = () => {
  showRewardModal.value = false
  rewardErrors.value = {}
}

// 验证奖惩表单
const validateRewardForm = () => {
  const errors = {}

  if (!editingReward.value.teacherId) {
    errors.type = '请输入教师号'
  }

  if (!editingReward.value.teacherName) {
    errors.type = '请输入教师名称'
  }
  if (editingReward.value.type !== 1 && editingReward.value.type !== 2) {
    errors.type = '请选择奖惩类型'
  }

  if (!editingReward.value.level.trim()) {
    errors.reason = '请输入奖惩级别'
  }

  if (!editingReward.value.date) {
    errors.date = '请选择日期'
  }

  rewardErrors.value = errors
  return Object.keys(errors).length === 0
}

// 保存奖惩记录
const saveReward = async () => {


  try {
    let response;
    if(showEditModal.value) {
        response = await fetch('/api/reward-punishment', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editingReward.value)
      })
    }
    else{
        response = await fetch('/api/reward-punishment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editingReward.value)
      })
    }

    const data = await response.json()

    if (data.code === 200) {
      alert(editingReward.value.type === 1 ? '奖励添加成功' : '惩罚添加成功')
      closeRewardModal()
      // 更新当前教师的奖惩记录
      fetch(`/api/reward-punishment?teacherId=${editingReward.value.teacherId}`)
          .then(res => res.json())
          .then(rewardData => {
            if (rewardData.code === 200) {
              rewards.value = rewardData.data || []
            }
          })
      showRewardModal.value = false
      showAddModal.value = false
      showEditModal.value = false
    } else {
      throw new Error(data.msg || '操作失败')
    }
  } catch (error) {
    alert(`操作失败: ${error.message}`)
    console.error('保存奖惩记录失败:', error)
  }
}

// 删除奖惩记录
const deleteReward = (id, index) => {
  if (confirm('确定要删除这条奖惩记录吗？')) {
    fetch(`/api/reward-punishment/${id}`, {
      method: 'DELETE'
    })
        .then(response => response.json())
        .then(data => {
          if (data.code === 200) {
            alert('奖惩记录删除成功')
            // 从本地数据中移除
            rewards.value.splice(index, 1)
          } else {
            throw new Error(data.msg || '删除失败')
          }
        })
        .catch(error => {
          alert(`删除失败: ${error.message}`)
          console.error('删除奖惩记录失败:', error)
        })
  }
}
</script>

<style scoped>
/* 导入Font Awesome */
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

/* 基础样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
}

h1 {
  font-size: 24px;
  color: #333;
}


/* 操作栏样式 */
.action-bar {
  display: flex;
  justify-content: flex-end;
}

/* 表格样式 */
.table-container {
  width: 100%;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.reward-table {
  width: 100%;
  border-collapse: collapse;
}

.reward-table th, .reward-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.reward-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #555;
  text-transform: uppercase;
  font-size: 12px;
}

.reward-table tr:last-child td {
  border-bottom: none;
}

.hover-row:hover {
  background-color: #f9f9f9;
  transition: background-color 0.2s ease;
}

/* 空状态样式 */
.empty-state {
  padding: 40px;
  text-align: center;
}

.empty-icon {
  color: #ccc;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  width: 100%;
  transform: scale(0.95);
  transition: transform 0.2s ease;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.modal-body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
}

.modal-content:hover {
  transform: scale(1);
}

/* 表单样式 */
.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  line-height: 20px;
  color: #333;
  background-color: white;
  background-clip: padding-box;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
  border-color: #6366f1;
  outline: 0;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3);
}

/* 按钮样式 */
button {
  cursor: pointer;
  border: none;
  background-color: transparent;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s ease;
}

button:hover {
  opacity: 0.9;
}

button:focus {
  outline: 0;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3);
}

.bg-blue-500 {
  background-color: #3b82f6;
  color: white;
}

.bg-green-500 {
  background-color: #22c55e;
  color: white;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.text-green-500 {
  color: #22c55e;
}

.text-red-500 {
  color: #ef4444;
}


.px-4 {
  padding-left: 1rem;
  padding-right: 1rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.rounded-md {
  border-radius: 0.375rem;
}

/* 错误提示样式 */
.text-red-500 {
  color: #ef4444;
}

.text-sm {
  font-size: 0.875rem;
}

.mt-1 {
  margin-top: 0.25rem;
}

.education-list > div, .family-list > div {
  position: relative;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
}

.text-xs {
  font-size: 0.75rem;
}

.font-medium {
  font-weight: 500;
}

.text-gray-800 {
  color: #1f2937;
}

.rounded-full {
  border-radius: 9999px;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.inline-block {
  display: inline-block;
}

.w-2 {
  width: 0.5rem;
}

.h-2 {
  height: 0.5rem;
}

.bg-blue-500 {
  background-color: #3b82f6;
}

.bg-green-500 {
  background-color: #22c55e;
}

.rounded-full {
  border-radius: 9999px;
}

.mr-1 {
  margin-right: 0.25rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

.mr-3 {
  margin-right: 0.75rem;
}

.text-base {
  font-size: 1rem;
}

.font-medium {
  font-weight: 500;
}

.text-gray-900 {
  color: #111827;
}

.transition-colors {
  transition: color 0.2s ease, background-color 0.2s ease;
}
</style>

